<template>
  <el-dialog
    :close-on-click-modal="false"
    :before-close="closeDialog"
    :visible.sync="dialogVisible"
    :title="isEdit ? '编辑会员卡信息' : '开卡'"
    width="600px"
    :modal-append-to-body="true"
    @closed="handleClosed"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      size="small"
      label-width="100px"
    >
      <el-form-item v-if="!isEdit" label="卡号" prop="cardNo">
        <div class="input-with-button">
          <el-input 
            v-model="form.cardNo" 
            :readonly="true"
            placeholder="点击右侧按钮获取卡号"
          />
          <el-button 
            @click="generateCardNumber" 
            type="primary"
            size="small"
          >获取卡号</el-button>
        </div>
      </el-form-item>

      <el-form-item v-if="!isEdit" label="卡类型" prop="cardType">
        <el-select v-model="form.cardType" filterable placeholder="请选择">
          <el-option
            v-for="item in dict.card_type"
            :key="item.id"
            :label="item.label"
            :value="item.value"
            :disabled="checkCardTypeDisabled(item.value)"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="有效期至">
        <el-date-picker
          v-model="form.validEndTime"
          type="date"
          style="width: 100%"
          placeholder="选择有效期"
        />
      </el-form-item>

      <template v-if="!isEdit">
        <el-form-item label="赠送次数">
          <el-input v-model="form.giftCount" />
        </el-form-item>

        <el-form-item label="支付方式">
          <el-select v-model="form.paymentMethod" filterable placeholder="请选择">
            <el-option
              v-for="item in dict.payment_method"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="收取金额" prop="amount">
          <el-input v-model="form.amount" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="item in dict.card_status"
              :key="item.id"
              :label="item.value"
            >{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="form.remarks"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="closeDialog">取消</el-button>
      <el-button :loading="loading" type="primary" @click="submitForm">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import crudMemberCards, { generateCardNumber } from "@/api/vip/card";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";

const defaultForm = {
  id: null,
  cardNo: null,
  cardType: null,
  memberId: null,
  petId: null,
  validEndTime: null,
  giftCount: 0,
  paymentMethod: null,
  amount: null,
  status: 'NORMAL',
  remarks: null,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null,
};

export default {
  name: "MemberCards",
  components: { pagination, crudOperation, rrOperation, udOperation },
  cruds() {
    return CRUD({ title: '会员卡管理', url: 'api/memberCards', idField: 'id', sort: 'id,desc', crudMethod: { ...crudMemberCards }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ["card_type", "payment_method", "card_status"],
  
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    member: {
      type: Object,
      default: () => null
    },
    memberCards: {
      type: Array,
      default: () => []
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    editingCard: {
      type: Object,
      default: () => null
    }
  },

  data() {
    return {
      dialogVisible: false,
      loading: false,
      permission: {
        add: ["admin", "memberCards:add"],
        edit: ["admin", "memberCards:edit"],
        del: ["admin", "memberCards:del"],
      },
      rules: {
        cardNo: [{ required: true, message: "卡号不能为空", trigger: "blur" }],
        cardType: [
          { required: true, message: "会员卡类型不能为空", trigger: "blur" },
        ],
        memberId: [
          { required: true, message: "会员ID不能为空", trigger: "blur" },
        ],
        amount: [
          { required: true, message: "收取金额不能为空", trigger: "blur" },
        ],
      },
      queryTypeOptions: [
        { key: "cardType", display_name: "会员卡类型" },
        { key: "paymentMethod", display_name: "支付方式" },
        {
          key: "status",
          display_name: "状态：NORMAL-正常 EXPIRED-已过期 DISABLED-已禁用",
        },
      ],
    };
  },

  watch: {
    visible: {
      immediate: true,
      handler(val) {
        this.dialogVisible = val;
      }
    },
    member: {
      handler(val) {
        if (val) {
          this.form.memberId = val.id;
        }
      },
      immediate: true
    },
    editingCard: {
      handler(val) {
        console.log('Received editing card:', val)
        if (val) {
          this.form = {
            id: val.id,
            cardNo: val.cardNo,
            cardType: val.cardType,
            memberId: val.memberId,
            validEndTime: val.validEndTime,
            giftCount: val.giftCount,
            paymentMethod: val.paymentMethod,
            amount: val.amount,
            status: val.status || 'NORMAL',
            remarks: val.remarks
          }
        }
      },
      immediate: true
    }
  },

  methods: {
    closeDialog() {
      this.dialogVisible = false;
    },

    handleClosed() {
      this.$emit("update:visible", false);
      this.$refs.form.resetFields();
      Object.assign(this.form, defaultForm);
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const request = this.isEdit 
            ? crudMemberCards.edit(this.form)
            : crudMemberCards.add(this.form)

          request.then(() => {
            this.$notify({
              title: '成功',
              type: 'success',
              message: this.isEdit ? '编辑成功' : '开卡成功'
            })
            this.loading = false
            this.closeDialog()
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },

    [CRUD.HOOK.beforeRefresh]() {
      return true;
    },

    generateCardNumber() {
      this.loading = true;
      generateCardNumber()
        .then(response => {
          this.form.cardNo = response;
        })
        .catch(error => {
          this.$notify.error({
            title: '错误',
            message: '获取卡号失败'
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },

    checkCardTypeDisabled(cardType) {
      console.log('Current member cards:', this.memberCards);
      console.log('Checking card type:', cardType);
      const isDisabled = this.memberCards.some(card => card.cardType === cardType);
      console.log('Is disabled:', isDisabled);
      return isDisabled;
    }
  },
};
</script>
  
<style scoped>
.input-with-button {
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-with-button .el-input {
  flex: 1;
}

:deep(.el-select),
:deep(.el-date-editor),
:deep(.el-input) {
  width: 100%;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
}
</style>
  